import Vue from 'vue'
import { getToken } from '@/api/storage'
import { Toast } from 'vant'
import VueRouter from 'vue-router'

const Register = () => import('@/views/Register')
const Login = () => import('@/views/Login')
const Detail = () => import('@/views/Detail')
const Layout = () => import('@/views/Layout')
const Article = () => import('@/views/Article')
const Collect = () => import('@/views/Collect')
const Like = () => import('@/views/Like')
const User = () => import('@/views/User')

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/article' },
  { path: '/register', component: Register }, // 注册页面
  { path: '/login', component: Login }, // 登录页面
  { path: '/detail/:id', component: Detail }, // 详情页面
  {
    path: '/',
    component: Layout,
    children: [
      { path: '/article', component: Article },
      { path: '/collect', component: Collect },
      { path: '/like', component: Like },
      { path: '/user', component: User }
    ]
  } // 首页
]
const router = new VueRouter({
  routes
})

const whiteList = ['/login', '/register']
const wmustList = ['/detail', '/article', '/collect', '/like', '/user']
// 导航守卫=》 全局前置守卫
router.beforeEach((to, from, next) => {
  // 执行时机：每次跳转都会触发该函数
// 只要注册了全局守卫，路由就会立即失效，必须调用 next() 方法来放心
// 参数1：to 到哪里去
// 参数2：from从哪里来
// 参数3：next函数，决定是否放行，next()表示放行，next('路径') 表示强制跳转到指定路由，next(false) 表示不放行
  // next()
  const token = getToken()
  console.log(token, 'token')
  if (token) {
    next() // 如果有登录token  放行
  } else {
    if (wmustList.includes(to.path)) {
      Toast.fail('您还未登录，请登录')
      next('/login')
    }
    // if (to.path === '/login' || to.path === '/register') {
    if (whiteList.includes(to.path)) {
      next() // 如果没有 可以去login或者register
    } // else {
    //   Toast.fail('您还未登录，请登录')
    //   next('/login') // 只能去login
    // }
  }
})

// 后置守卫
// router.afterEach

export default router
